package tools

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"net/url"
	"os"
	"strings"
)

// HttpPostForm 发送http post请求数据为form
func HttpPostForm(url string, data url.Values, header map[string]string) (response string, err error) {
	req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
	if err != nil {
		return
	}
	//req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	//req.Header.Set("Authorization", "12346")
	for k, v := range header {
		req.Header.Set(k, v)
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	content, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
}

func HttpPost(url, postData string, headers map[string]string) (responseData string, err error) {
	request, _ := http.NewRequest("POST", url, strings.NewReader(postData))
	if headers["Content-Type"] == "" {
		headers["Content-Type"] = "application/json"
	}
	if headers["Accept"] == "" {
		headers["Accept"] = "application/json"
	}
	for key, val := range headers {
		request.Header.Add(key, val)
	}
	resp, err := http.DefaultClient.Do(request) // 发送请求
	defer resp.Body.Close()
	if err != nil {
		return
	} else {
		byteData, err2 := io.ReadAll(resp.Body)
		if err2 != nil {
			err = err2
			return
		}
		responseData = string(byteData)
	}
	return
}

// HttpPostMultipart 发送http post请求上传文件
func HttpPostMultipart(url string, filePath string, postData url.Values, header map[string]string) (response string, err error) {
	file, err := os.Open(filePath)
	if err != nil {
		return
	}
	defer func() { _ = file.Close() }()
	// 创建一个内存缓冲区,创建一个 multipart writer
	formBody := &bytes.Buffer{}
	writer := multipart.NewWriter(formBody)
	part, err := writer.CreateFormFile("file", file.Name()) // 添加文件字段
	if err != nil {
		return
	}

	if _, err = io.Copy(part, file); err != nil {
		return
	}
	for k, v := range postData {
		field, err3 := writer.CreateFormField(k) // 添加普通文本字段
		_, _ = field.Write([]byte(v[0]))
		if err3 != nil {
			return
		}
	}
	_ = writer.Close()
	req, err := http.NewRequest("POST", url, formBody)
	if err != nil {
		return
	}
	for k, v := range header {
		req.Header.Set(k, v)
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	//req.Header.Set("Content-Type", "multipart/form-data; boundary="+writer.Boundary())

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer func() { _ = resp.Body.Close() }()
	content, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
}

func HttpGet(reqUrl string) (respBody []byte, err error) {
	resp, err := http.Get(reqUrl) //发起get请求
	if err != nil {
		return
	}
	defer resp.Body.Close()               //关闭请求
	respBody, err = io.ReadAll(resp.Body) //解析请求信息
	if err != nil {
		return
	}
	return
}
